package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 检查用户是否完成登录

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器, 支持通配符, 用于路径比较
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1. 获取本次请求的URI
        String requestURI = request.getRequestURI();  // ** 注意千万不要写成URL
/*        String requestURL = request.getRequestURL().toString();
        log.info("URI: {}",requestURI);     //   /employee/page
        log.info("URL: {}",requestURL);     //   http://localhost:8080/employee/page
*/
        //不需要过滤的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",  //移动端发送短信
                "/user/login"   //移动端登录
        };

        /*
            注意:
                @WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
                    这里 /* 由tomcat解析, 支持任意路径的匹配
                "/backend/**"
                    这里的通配符由spring的工具类 AntPathMatcher 解析
                     "/backend/*" 里面的 * 代表的是一层目录任意
                      "/backend/**" 里面的 * 代表的是多层目录任意 例如: /backend/page/login/login.html
         */

        //2. 判断本次请求是否需要处理
        boolean flag = check(requestURI, urls);

        //3. 匹配成功, 无需处理直接放行
        if (flag) {
            log.info("本次请求{}不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        //4-1. 匹配失败, 判断登陆状态, 如果已登录, 则放行
        if (request.getSession().getAttribute("employee") != null) {
            log.info("用户已登录,id为{}", request.getSession().getAttribute("employee"));

            Long employeeId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(employeeId);

            filterChain.doFilter(request, response);
            return;
        }

        //4-2. 匹配失败, 判断移动端登陆状态, 如果已登录, 则放行
        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登录,id为{}", request.getSession().getAttribute("user"));

            Long employeeId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(employeeId);

            filterChain.doFilter(request, response);
            return;
        }
        //5. 未登录, 返回未登录结果
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    // 路径匹配,检测本次请求是否需要放行
    public boolean check(String requestURI, String[] urls) {
        for (String url : urls) {
            boolean flag = PATH_MATCHER.match(url, requestURI);
            if (flag) {
                return true;
            }
        }
        return false;
    }
}
